package com.security.common;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.util.RedirectUrlBuilder;

import com.security.controller.SecurityController;

/**
 * 异常登录切入点
 * @author chengr
 *
 */
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
	//登录地址
	private String loginpath;
	public void setLoginpath(String loginpath) {
		this.loginpath = loginpath;
	}
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		SecurityController.formatHeader(response);
		response.getWriter().print(loginpath);
	}
	/**
	 * 获取当前被 （登录前）被拦截的URL
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	protected String buildHttpReturnUrlForRequest(HttpServletRequest request)
            throws IOException, ServletException {
        RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
        urlBuilder.setScheme(request.getScheme());
        urlBuilder.setServerName(request.getServerName());
        urlBuilder.setPort(request.getServerPort());
        urlBuilder.setContextPath(request.getContextPath());
        urlBuilder.setServletPath(request.getServletPath());
        urlBuilder.setPathInfo(request.getPathInfo());
        urlBuilder.setQuery(request.getQueryString());
        return urlBuilder.getUrl();
    }

}
